/* 
用户搜索模块的vuex模块
*/
import axios from 'axios'

export default {
  namespaced: true, // 开启命名空间
  state: {
    firstView: true,
    loading: false,
    users: [],
    errorMsg: ''
  },

  mutations: {
    // 变为请求
    requesting (state) {
      state.firstView = false
      state.loading = true
    },

    // 请求成功后, 更新为成功
    reqSuccess (state, users) {
      state.users = users
      state.loading = false
    },

    // 请求失败后, 更新为失败
    reqError (state, errorMsg) {
      state.loading = false
      state.errorMsg = errorMsg
    }
  },

  actions: {
    // 请求搜索用户列表的异步action
    async search ({commit}, keyword) {
       // 更新为请求中
      commit('requesting')
       try {
         // 发请求获取用户列表
         const response = await axios.get(`/dev-api/search/users?q=${keyword}`)
 
         // 请求成功后, 更新为成功的状态
         // 读取成功数据中的用户列表
         const users = response.data.items.map(item => ({
           name: item.login,
           url: item.html_url,
           avatar_url: item.avatar_url
         }))
         commit('reqSuccess', users)
        
       } catch (error) {
         // 更新为失败
         commit('reqError', '请求失败: ' + error.message)
       }
    }
  },

  getters: {

  }
}